<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>教师管理系统</title>
    <script src="/js/jquery-3.7.1.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/style.css">

</head>
<body>

<header>
    <h1>教师管理系统111</h1>
</header>

<nav>
    <a href="${pageContext.request.contextPath}/teacherlist.jsp">教师管理</a>
    <a href="${pageContext.request.contextPath}/Classes.jsp">班级管理</a>
    <a href="#">系统设置</a>
</nav>

<div class="search-container">
    <label for="search">搜索教师:</label>
    <input type="text" id="search" placeholder="请输入教师姓名...">
    <button id="sousuo" onclick="searchTeacher()">搜索</button>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <button id="tianjiajiaoshi" onclick="addTeacher()">添加教师</button>
</div>
<table class="teachers-list">
    <thead>
    <tr>
        <th>教师ID</th>
        <th>姓名</th>
        <th>性别</th>
        <th>电话</th>
        <th>邮箱</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody id="teachersTable">
    <!-- 教师数据将通过 JavaScript 动态填充 -->
    </tbody>
</table>

<div class="pagination">
    <button id="prevPage" onclick="changePage(-1)">上一页</button>
    <span id="pageInfo">第 <span id="currentPage">1</span> 页，共 <span id="totalPages">1</span> 页</span>
    <button id="nextPage" onclick="changePage(1)">下一页</button>
</div>

<!-- 创建一个表单，使用POST方法提交到/logout -->
<form id="logoutForm" action="http://localhost:8080/user/logout" method="post">
    <!-- 这个隐藏的input是为了防止浏览器在非GET/HEAD请求中发送表单数据时弹出确认对话框 -->
    <input type="hidden" name="_method" value="POST">
</form>

<!-- 添加一个按钮，当点击时，通过JavaScript提交表单 -->
<button onclick="document.getElementById('logoutForm').submit();">退出</button>
<!-- 模态框 -->
<div id="updateModal" >
    <div>
        <h2 id="modalTitle">标题</h2>
        <label for="teacherID">教师ID:</label>
        <input type="text" id="teacherID" disabled>
        <br>
        <label for="name">姓名:</label>
        <input type="text" id="name">
        <br>
        <label for="gender">性别:</label>
        <select id="gender">
            <option value="男">男</option>
            <option value="女">女</option>
        </select>
        <br>
        <label for="phone">电话:</label>
        <input type="text" id="phone">
        <br>
        <label for="email">邮箱:</label>
        <input type="text" id="email">
        <br>
        <button id="confirmUpdate">确认</button>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <button onclick="closeModal()">取消</button>
    </div>
</div>


</body>
<script>
    let currentPage = 1;
    let totalPages = 1;
    const pageSize = 5; // 每页显示的记录数
    var currentteacherlist;

    $(document).ready(function() {
        console.log("aaa")
        loadTeachers(currentPage);
    });

    function loadTeachers(page) {
        $.ajax({
            url: 'http://localhost:8080/teacher/getTeacherListByPage',
            method: 'GET',
            data: {
                pageNumber: page,
                pageSize: pageSize,
                search:$('#search').val()

            },
            success: function(response) {
                console.log(response)
                const teachers = response.dataList;
                totalPages = response.totalPages;
                updateTable(teachers);
                updatePagination();
            },
            error: function(xhr, status, error) {
                console.error("加载教师数据失败:", error);
                window.location.href = '/login.jsp';
            }
        });
    }

    //更新表格
    function updateTable(teachers) {
        const tbody = $('#teachersTable');
        currentteacherlist=teachers
        console.log()
        tbody.empty();
        teachers.forEach(function(teacher) {
            console.log(teacher)
            tbody.append(`
                <tr>
                    <td>`+teacher.teacherID+`</td>
                    <td>`+teacher.name+`</td>
                    <td>`+teacher.gender+`</td>
                    <td>`+teacher.phone+`</td>
                    <td>`+teacher.email+`</td>
                    <td>
                        <button class="table-button update" onclick="updateTeacher(`+teacher.teacherID+`)">
                            更新
                        </button>
                        <button class="table-button delete" onclick="deleteTeacher(`+teacher.teacherID+`)">
                            删除
                        </button>
                    </td>


                </tr>
            `);
        });
    }

    function updatePagination() {

        $('#currentPage').text(currentPage);
        $('#totalPages').text(totalPages);
        $('#prevPage').prop('disabled', currentPage === 1);
        $('#nextPage').prop('disabled', currentPage === totalPages);
    }

    function changePage(delta) {
        currentPage += delta;
        loadTeachers(currentPage);
    }

    function searchTeacher() {
        const searchQuery = $('#search').val();
        console.log(searchQuery)
        currentPage = 1; // 重置到第一页
        loadTeachers(currentPage);
    }

    function updateTeacher(teacherID) {
        $('#modalTitle').val("更新");
        console.log("updateTeacher")
        console.log("当前id",teacherID)
        let teacher = null
        console.log(currentteacherlist)
        for (let i = 0; i < currentteacherlist.length; i++) {
            if (currentteacherlist[i].teacherID === teacherID) {
                teacher = currentteacherlist[i];
                break; // 找到对象后退出循环
            }
        }
        console.log("teacher",teacher)
        // 使用教师对象填充模态框中的信息
        $('#teacherID').val(teacher.teacherID);
        $('#name').val(teacher.name);
        $('#gender').val(teacher.gender);
        $('#phone').val(teacher.phone);
        $('#email').val(teacher.email);

        // 显示模态框
        $('#updateModal').fadeIn();

        // 确认更新按钮的事件
        $('#confirmUpdate').off('click').on('click', function() {
            const updatedTeacher = {
                teacherID: $('#teacherID').val(),
                name: $('#name').val(),
                gender: $('#gender').val(),
                phone: $('#phone').val(),
                email: $('#email').val()
            };

            // 发送更新请求
            $.ajax({
                url: 'http://localhost:8080/teacher/updateTeacherById', // 替换为实际的API端点
                method: 'POST',
                data: updatedTeacher,
                success: function(response) {
                    console.log("更新成功:", response);
                    loadTeachers(currentPage); // 刷新教师列表
                    $('#updateModal').hide(); // 关闭模态框
                },
                error: function(xhr, status, error) {
                    console.error("更新失败:", error);
                }
            });
        });
    }
    function closeModal(){
        $('#updateModal').hide();
    }

    function deleteTeacher(teacherID) {
        console.log(teacherID)
        if (confirm("确定要删除该教师吗？")) {
            $.ajax({
                url: 'http://localhost:8080/teacher/deleteTeacherbyId', // 替换为实际的API端点
                method: 'GET',
                data: {
                    teacherID: teacherID
                },
                success: function(response) {
                    console.log("删除成功:", response);
                    loadTeachers(currentPage); // 刷新教师列表
                },
                error: function(xhr, status, error) {
                    console.log(teacherID)
                    console.error("删除失败:", error);
                }
            });
        }
    }

    function addTeacher() {
        $('#modalTitle').val("添加");
        // 显示模态框
        $('#updateModal').fadeIn();
        $('#teacherID').prop('disabled', true);
        // 确认添加按钮的事件
        $('#confirmUpdate').off('click').on('click', function() {
            const addTeacher = {
                name: $('#name').val(),
                gender: $('#gender').val(),
                phone: $('#phone').val(),
                email: $('#email').val()
            };

            // 发送更新请求
            $.ajax({
                url: 'http://localhost:8080/teacher/addTeacher', // 替换为实际的API端点
                method: 'POST',
                data: addTeacher,
                success: function(response) {
                    if (response === "添加成功"){
                        console.log("添加成功:", response);
                        loadTeachers(currentPage); // 刷新教师列表
                        $('#updateModal').hide(); // 关闭模态框
                    }else {
                        alert("添加失败")
                        loadTeachers(currentPage); // 刷新教师列表
                        $('#updateModal').hide(); // 关闭模态框
                    }

                },
                error: function(xhr, status, error) {
                    console.error("添加失败:", error);
                }
            });
        });
    }
</script>

</html>